package com.javaedge.concurrency;

import com.javaedge.concurrency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author JavaEdge
 */
@Slf4j
@NotThreadSafe
public class semaphoreTest {

    // 同时并发执行的线程数
    public static int threadTotal = 5;

    public static void main(String[] args) throws Exception {
        final Semaphore semaphore = new Semaphore(threadTotal);
        log.info("初始化:{}个银行柜台窗口", threadTotal);
        for (int i = 0; i < 10 ; i++) {
            Thread.sleep(1000L);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        log.info("用户{}占用窗口", Thread.currentThread().getName());
                        semaphore.acquire(1);
                        log.info("用户{}开始办理业务", Thread.currentThread().getName());
                        Thread.sleep(5000L);
                        semaphore.release();
                        log.info("用户{}离开窗口", Thread.currentThread().getName());
                    } catch (Exception e) {
                        log.error("exception", e);
                    }
                }
            }).start();
        }
    }

}
